//
//  CommentsViewController.m
//  myhuibao
//
//  Created by lijun on 13-3-19.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//

#import "CommentsViewController.h"
#import <UIKit/UIKit.h>
#import "Config.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJson.h"
#import "CommentsCell.h"
#import "CommentDetailViewController.h"
#import "CommentsInfoViewController.h"
#import "MainTabViewController.h"
#import "LoadMoreCell.h"
#import "OMGToast.h"


@interface CommentsViewController ()

@end

@implementation CommentsViewController
@synthesize maintable;
@synthesize req;
@synthesize reqMore;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    wqTable=maintable;
    pageIndex=1;
    NSString *spageIndex=[NSString stringWithFormat:@"%d",pageIndex];
    int merchantId=[[Config Instance] getMemberId];
    NSString *password=[[Config Instance] getPassword];
    NSString *sid=[NSString stringWithFormat:@"%d",merchantId];
    NSURL *url = [NSURL URLWithString:url_dealList];
    req =[ASIFormDataRequest requestWithURL:url];
    [req setPostValue:sid forKey:@"memberID"];
    [req setPostValue:password forKey:@"password"];
    [req setPostValue:spageIndex forKey:@"pageIndex"];
    [req setShouldAttemptPersistentConnection:NO];
    [req setDidFinishSelector:@selector(finishReq:)];
    isReqFinished = false;
    [req setDelegate: self];
    
    [req startAsynchronous];
   
}

- (void)viewDidUnload
{
    [self setMaintable:nil];
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

//异步请求的二个方法
-(void) finishReq:(ASIFormDataRequest *)request
{
    isReqFinished = true;
    NSString *jsonStr=[request responseString];
    NSDictionary *dic=[jsonStr JSONValue];
    if(![[dic valueForKey:@"status"] isEqualToString:@"SUCCESS"]){
        UIAlertView *view=[[UIAlertView alloc]initWithTitle:APP_TITLE message:[[dic valueForKey:@"log"] isEqualToString:@""]?@"未获取到待点评消费信息":[dic valueForKey:@"log"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [view show];
        return;
    }
//    NSLog(@"%@",dic);
    tableDataArray=[[NSMutableArray alloc] initWithCapacity:10];
    NSMutableArray *array = [dic valueForKey:@"data"];
    for(int i=0;i<array.count;i++)
    {
        if([[[array objectAtIndex:i] objectForKey:@"ORDERTYPEID"] intValue]!=0)
        {
            [tableDataArray addObject:[array objectAtIndex:i]];
        }
    }
    returnCount = [tableDataArray count];
    if (returnCount==0) {
        [OMGToast showWithText:@"无待点评交易" bottomOffset:100];
    }
    delegate=self;
    [maintable reloadData];
    [Config setExtraCellLineHidden:maintable];

}
-(void) requestFailed:(ASIFormDataRequest *)request{
    NSError *error=[request error];
    NSLog(@"%@",error);
    if (error.code==net_failure_code) {
        [OMGToast showWithText:net_failure_msg bottomOffset:100];
    }
    isReqFinished = true;
    isReqMoreFinished = true;
}
-(NSInteger )tableView:(UITableView *) tableView numberOfRowsInSection:(NSInteger)section{
    int count=[tableDataArray count];
    if (count>=pageSize) {
        return count+1;
    }else
        return count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([indexPath row] < ([tableDataArray count])) {
        return 90;
    }else{
        return 40;
    }
}
- (CGFloat)tableView:(UITableView *)tableView widthForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 320;
}

-(UITableViewCell *) tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"CommentsCellIdentifier";
    if([indexPath row] < ([tableDataArray count])) {
        CommentsCell *cell = (CommentsCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
                if (cell == nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"CommentsCell" owner:nil options:nil];
        cell = [array objectAtIndex:0];
        [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
                }
        
        NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
        cell.merchantName = [item valueForKey:@"MERCHANTNAME"];
        cell.payType = [item valueForKey:@"PAYTYPENAME"] ;
        cell.dealValue = [item valueForKey:@"DEALVALUE"];
        cell.dealDate = [item valueForKey:@"DEALDATE"];
        return cell;
    }else{
        LoadMoreCell *cell = (LoadMoreCell *)[tableView dequeueReusableCellWithIdentifier: @"LoadMoreCellIdentifier"];
        if (cell==nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"LoadMoreCell" owner:nil options:nil];
            cell = [array objectAtIndex:0];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        if(returnCount<pageSize){
            cell.lbText.text=@"";
            cell.hidden = true;
        }else{
            //创建loadMoreCell
            cell.lbText.text=str_more;
        }
        cell.textLabel.textAlignment = UITextAlignmentCenter;
        cell.detailTextLabel.text=@"";
        cell.imageView.image =nil;
        return cell;
//        UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//        //              if (cell == nil)
//        {
//            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
//                                          reuseIdentifier:CellIdentifier];
//            cell.selectionStyle = UITableViewCellSelectionStyleNone;
//        }
//        if(returnCount<pageSize){
//            cell.textLabel.text=@"";
//        }else{
//            //创建loadMoreCell
//            cell.textLabel.text=str_more;
//        }
//        cell.textLabel.textAlignment = UITextAlignmentCenter;
//        cell.detailTextLabel.text=@"";
//        cell.imageView.image =nil;
//        return cell;

    }
    /*
    static NSString *CellIdentifier=@"CommentsCellIdentifier";
    if([indexPath row]<([tableDataArray count])){
        CommentsCell *cell = (CommentsCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"CommentsCell" owner:nil options:nil];
        cell = [array objectAtIndex:0];
        [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
        NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
        cell.merchantName = [item valueForKey:@"MERCHANTNAME"];
        cell.payType = [item valueForKey:@"PAYTYPENAME"] ;
        cell.dealValue = [item valueForKey:@"DEALVALUE"];
        cell.dealDate = [item valueForKey:@"DEALDATE"];
        return cell;
    }else{
        UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        //              if (cell == nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                          reuseIdentifier:CellIdentifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        return cell;
    }
     */
}
//点击cell时候
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == [tableDataArray count]) {
//        UITableViewCell *loadMoreCell=[tableView cellForRowAtIndexPath:indexPath];
//        loadMoreCell.textLabel.text=str_loading;
        //        [self performSelectorInBackground:@selector(loadMore) withObject:nil];
        //        [tableView deselectRowAtIndexPath:indexPath animated:YES];
//        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?pageIndex=%d",url_commentDeatil,pageIndex++]] ;
//        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
//        [request startSynchronous];
//        NSString *jsonStr = [request responseString];
//        
//        NSDictionary *dic = [jsonStr JSONValue];
//        NSMutableArray *array = [dic valueForKey:@"data"];
//        returnCount = [array count];
//        [self performSelectorOnMainThread:@selector(appendTableWith:) withObject:array waitUntilDone:NO];
//        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        //        [dic release];
        //        [array release];
        LoadMoreCell *loadMoreCell=(LoadMoreCell *)[tableView cellForRowAtIndexPath:indexPath];
        loadMoreCell.lbText.text=str_loading;
        NSString *spageIndex=[NSString stringWithFormat:@"%d",++pageIndex];
        int merchantId=[[Config Instance] getMemberId];
        NSString *password=[[Config Instance] getPassword];
        NSString *sid=[NSString stringWithFormat:@"%d",merchantId];
        NSURL *url = [NSURL URLWithString:url_dealList];
        reqMore=[ASIFormDataRequest requestWithURL:url];
        [reqMore setPostValue:sid forKey:@"memberID"];
        [reqMore setPostValue:password forKey:@"password"];
        [reqMore setPostValue:spageIndex forKey:@"pageIndex"];
        reqMore.delegate = self;
        isReqMoreFinished = false;
        [reqMore setShouldAttemptPersistentConnection:NO];
        [reqMore setDidFinishSelector:@selector(appendTableWith:)];
        [reqMore startAsynchronous];

        return;
    }else{
        CommentDetailViewController  *view = [[CommentDetailViewController alloc] initWithNibName:@"CommentDetailViewController" bundle:nil];
        //传递商户id参数
        NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
        
        
        view.merchantId =[[item objectForKey:@"MERCHANTID"] intValue];
        view.dealId=[[item objectForKey:@"DEALID"] intValue];
        view.mName = [item valueForKey:@"MERCHANTNAME"];
        view.merchantType=[[item valueForKey:@"ORDERTYPEID"] intValue];
        view.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:view animated:YES];
        //[view release];
    }
    //其他cell的事件
    /*
    if (indexPath.row == [tableDataArray count]) {
        UITableViewCell *loadMoreCell=[tableView cellForRowAtIndexPath:indexPath];
        loadMoreCell.textLabel.text=str_loading;
        //        [self performSelectorInBackground:@selector(loadMore) withObject:nil];
        //        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:url_commentDeatil] ];
        ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
                [request startSynchronous];
        NSString *jsonStr = [request responseString];
        
        NSDictionary *dic = [jsonStr JSONValue];
        NSMutableArray *array = [dic valueForKey:@"data"];
        returnCount = [array count];
        //[dic release];
        //[array release];
        return;
    }else{
        CommentDetailViewController  *view = [[CommentDetailViewController alloc] initWithNibName:@"CommentDetailViewController" bundle:nil];
        //传递商户id参数
        NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
        
        view.merchantId =[[item objectForKey:@"MERCHANTID"] intValue];
        view.dealId=[[item objectForKey:@"DEALID"] intValue];
        view.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:view animated:YES];
        [view release];
        
    }
    //其他cell的事件
    */
}
//-(void) appendTableWith:(NSMutableArray *)data
//{   //将loadMore中的NSMutableArray添加到原来的数据源listData中.
//    for (int i=0;i<[data count];i++) {
//        [tableDataArray addObject:[data objectAtIndex:i]];
//    }
//    NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:pageSize];
//    for (int ind = 0; ind < [data count]; ind++) {
//        NSIndexPath    *newPath =  [NSIndexPath indexPathForRow:[tableDataArray indexOfObject:[data objectAtIndex:ind]] inSection:0];
//        [insertIndexPaths addObject:newPath];
//    }
//    //重新调用UITableView的方法, 来生成行.
//    [self.maintable insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
//}
-(void) appendTableWith:(ASIHTTPRequest *)request
{   //将loadMore中的NSMutableArray添加到原来的数据源listData中.
    isReqMoreFinished = true;
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    NSMutableArray *data = [dic valueForKey:@"data"];
    returnCount = [data count];
    //    [self performSelectorOnMainThread:@selector(appendTableWith:) withObject:array waitUntilDone:NO];
    for (int i=0;i<[data count];i++) {
        [tableDataArray addObject:[data objectAtIndex:i]];
    }
    NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:pageSize];
    for (int ind = 0; ind < [data count]; ind++) {
        NSIndexPath    *newPath =  [NSIndexPath indexPathForRow:[tableDataArray indexOfObject:[data objectAtIndex:ind]] inSection:0];
        [insertIndexPaths addObject:newPath];
    }
    if ([data count]==0) {
        [self.maintable reloadData];
    }
    //重新调用UITableView的方法, 来生成行.
    [self.maintable insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
//    isSearchMoreFinished = true;
}

//实现接口的方法
-(void)cellImageDidLoad:(NSIndexPath *)indexPath image:(UIImage *)image
{
    dispatch_async(dispatch_get_main_queue(), ^{
        UITableViewCell *cell = [wqTable cellForRowAtIndexPath:indexPath];
        if(image)
        {
            cell.imageView.image = image;
        }
    });
}
- (IBAction)goBack:(id)sender {
//    [super.navigationController popViewControllerAnimated:YES];
    if (!isReqFinished){
        [req clearDelegatesAndCancel];
        [req cancel];
    }
    if (!isReqMoreFinished){
        [reqMore clearDelegatesAndCancel];
        [reqMore cancel];
    }
    [super.navigationController popViewControllerAnimated:YES];
//    MainTabViewController *mainTabViewController;
//    mainTabViewController = [[MainTabViewController alloc] init];
//    [mainTabViewController selectViewController:3];
//    [self.view.window addSubview:mainTabViewController.view];
}
@end
